package com.randi.framework.security.handle;

import com.alibaba.fastjson2.JSON;
import com.randi.common.constant.Constants;
import com.randi.common.core.domain.Result;
import com.randi.common.enums.ResultCode;
import com.randi.common.utils.ServletUtils;
import com.randi.framework.domain.service.ISysTokenService;
import com.randi.system.service.SysLogThreadService;
import com.randi.common.core.domain.model.LoginUser;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义退出处理类
 *
 * @author randi
 */
@Configuration
public class LogoutHandlerImpl implements LogoutSuccessHandler {

    @Resource
    private ISysTokenService iSysTokenService;

    @Resource
    private SysLogThreadService sysLogThreadService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

        LoginUser loginUser = iSysTokenService.getLoginUser(request);
        if (loginUser != null) {
            iSysTokenService.removeTokenCache(loginUser.getUuid());
            sysLogThreadService.handleLoginInfo(loginUser.getUserName(), Constants.LOGIN_OUT, ResultCode.LOGIN_OUT_SUCCESS.message());
            String string = JSON.toJSONString(Result.success(ResultCode.LOGIN_OUT_SUCCESS));
            ServletUtils.renderString(response, string);
        } else {
            ServletUtils.renderString(response, JSON.toJSONString(Result.success(ResultCode.SUCCESS)));
        }
    }
}
